import { mapMutations, mapActions, mapState } from 'vuex';
import moment from 'moment'
let showLoadingCount = 0
let hideLoadingCount = 0
export default {
	data() {
		return {}
	},
	computed: {
		...mapState(['$isPc', '$hasLogin', '$userInfo', '$enums'])
	},
	methods: {
		...mapMutations(['login', 'loginToken']),
		...mapActions(['isPc', 'getUserInfo', 'logout', 'setEnums']),
		// 显示隐藏loading
		mxShowLoading(options) {
			uni.showLoading({
				title: options && options.title || "加载中...",
				mask: options && options.mask === false ? false : true,
				success: () => {
					if (options && options.success) {
						options.success()
					}
				},
				fail: () => {
					if (options && options.fail) {
						options.fail()
					}
				},
				complete: () => {
					showLoadingCount++
					if (options && options.complete) {
						options.complete()
					}
				}
			})
		},
		mxHideLoading() {
			hideLoadingCount++
			if (showLoadingCount <= hideLoadingCount) {
				showLoadingCount = 0
				hideLoadingCount = 0
				uni.hideLoading()
			}
		},
		// toast统一提示方便全局修改
		mxToast(title, opts, callback) {
			if(Boolean(title) === false){
				return false
			}
			showLoadingCount = 0
			hideLoadingCount = 0
			uni.showToast({
				title,
				duration: opts && opts.time || 1500,
				mask: opts && opts.mask || false,
				icon: opts && opts.icon || "none",
				complete: () => {
					if (callback) {
						setTimeout(() => {
							callback()
						}, opts && opts.time || 1500)
					}
				}
			})
		},
		mxHideToast() {
			showLoadingCount = 0
			hideLoadingCount = 0
			uni.hideToast()
		},
		/* 表格自动格式化日期 */
		mxTableDateFormat(row, column) {
			var date = row[column.property]
			return this.mxGetFormatDate(date)
		},
		// 日期时间转换为时间戳
		mxToUnixStamp(date) {
			return !date ? '' : moment(date).format("X")
		},
		// 根据传的日期时间，转换为指定格式
		mxGetFormatDate(date, isUnix, formatTime) {
			if (isUnix) {
				return !date ? '' : moment.unix(date).format(formatTime || 'YYYY-MM-DD HH:mm:ss')
			} else {
				return !date ? '' : moment(date).format(formatTime || 'YYYY-MM-DD HH:mm:ss')
			}
		},
		// get请求
		httpGet(options) {
			return new Promise((resolve, reject) => {
				this.mxShowLoading()
				uni.$u.http.get(options.url, options.params || {}).then(res => {
					this.mxHideLoading()
					resolve(res)
				}).catch(error => {
					this.httpCommonError(options, error, reject)
				})
			})
		},
		// post请求
		httpPost(options) {
			return new Promise((resolve, reject) => {
				this.mxShowLoading()
				uni.$u.http.post(options.url, options.params || {}, options.config || { auth: true }).then(res => {
					this.mxHideLoading()
					resolve(res)
				}).catch(error => {
					this.httpCommonError(options, error, reject)
				})
			})
		},
		// upload请求
		httpUpload(options) {
			return new Promise((resolve, reject) => {
				this.mxShowLoading()
				uni.$u.http.upload(options.url, options.params || {}).then(res => {
					this.mxHideLoading()
					resolve(res)
				}).catch(error => {
					this.httpCommonError(options, error, reject)
				})
			})
		},
		// put请求
		httpPut(options) {
			return new Promise((resolve, reject) => {
				this.mxShowLoading()
				uni.$u.http.put(options.url, options.params || {}, options.config || { auth: true }).then(res => {
					this.mxHideLoading()
					resolve(res)
				}).catch(error => {
					this.httpCommonError(options, error, reject)
				})
			})
		},
		// delete请求
		httpDelete(options) {
			return new Promise((resolve, reject) => {
				this.mxShowLoading()
				uni.$u.http.delete(options.url, options.params || {}).then(res => {
					this.mxHideLoading()
					resolve(res)
				}).catch(error => {
					this.httpCommonError(options, error, reject)
				})
			})
		},
		// 请求错误
		httpCommonError(options, error, reject) {
			// 错误提示
			let identity = this.mxSetIdentityVal()
			if (error.statusCode == 401) {
				this.mxToast("请先登录!", {
					time: 1500,
					mask: true
				}, () => {
					uni.reLaunch({
						url: '/pages/common/login/login?' + identity
					})
				})
			} else if (error.statusCode == 403) {
				this.mxToast("您无权访问本页面!", {
					time: 2000,
					mask: true
				}, () => {
					uni.reLaunch({
						urls: '/pages/common/login/login?' + identity
					})
				})
			} else if (error.statusCode == 500) {
				console.log(error.data)
				this.mxHideLoading()
				// 后台修改后的状态码 code = 0
				if (error.data && error.data.error && error.data.error.code === 0) {
					uni.showModal({
						title: "提示",
						content: error.data.error.details || error.data.error.message || "网络错误!"
					})
				}
			} else {
				this.mxToast(options.faildText || "网络错误!", { icon: "error" })
			}
			reject(error)
		},
		// 操作枚举对象
		getEnumConfigs(key) {
			// 根据key获取当前需要的对象数组
			let temp = {
				arrs: [], // 数组
				objs: {}  // 键值对
			}
			temp.arrs = this.$enums[key]
			for (let i in temp.arrs) {
				let item = temp.arrs[i]
				temp.objs[item.name] = {}
				for (let k in item) {
					if (k != "name") {
						temp.objs[item.name][k] = item[k]
					}
				}
			}
			return temp
		},
		// 获取枚举的值
		getEnumConfigsItem(items, name, key) {
			let back = ""
			if (items && items[name]) {
				if (items[name][key]) {
					back = items[name][key]
				} else if (items[name][key] === 0) {
					back = 0
				}
			}
			return back
		},
		// 清空指定属性的值
		mxClearable(params, vals) {
			for (let i in params) {
				let param = params[i]
				let val = vals[i]
				if (val === undefined || val === "") {
					eval("this." + param + "=''" );
				} else {
					eval("this." + param + "=" + val);
				}
			}
		},
		// 退出登录
		toLoginOrOut() {
			let that = this
			uni.showModal({
				title: "退出登录",
				content: "确定要退出登录吗?",
				success: res => {
					if (res.confirm) {
						let identity = this.mxSetIdentityVal()
						that.logout()
						window.location.href = this.$config.baseUrl + "/H5/#/pages/common/login/login?" + identity
						/* uni.reLaunch({
							url: '/pages/common/login/login?' + identity
						}) */
					}
				}
			})
		},
		// 下载excel提示
		mxDownExcelTips() {
			if (this.$tools.getBrowser().wechat) {
				this.mxToast("请使用外部浏览器保存!", { time: 2500 })
				return false
			}
			return true
		},
		// 保留当前页面，跳转到应用内的某个页面
		mxNavigateTo(options) {
			if (options && typeof options === "string") {
				options = {
					url: options
				}
			}
			if (!options || !options.url) {
				this.mxToast("Url不能为空!")
				return false
			}
			options.url = options.params ? `${options.url}?${this.$tools.jsonToUrlParams(options.params)}` : options.url
			uni.navigateTo({
				url: options.url,
				events: options.events || {},
				success: () => {
					if (options && options.success) {
						options.success()
					}
				},
				fail: () => {
					if (options && options.fail) {
						options.fail()
					}
				},
				complete: () => {
					if (options && options.complete) {
						options.complete()
					}
				}
			})
		},
		// 关闭当前页面，跳转到应用内的某个页面
		mxRedirectTo(options) {
			if (options && typeof options === "string") {
				options = {
					url: options
				}
			}
			if (!options || !options.url) {
				this.mxToast("Url不能为空!")
				return false
			}
			options.url = options.params ? `${options.url}?${this.$tools.jsonToUrlParams(options.params)}` : options.url
			uni.redirectTo({
				url: options.url,
				success: () => {
					if (options && options.success) {
						options.success()
					}
				},
				fail: () => {
					if (options && options.fail) {
						options.fail()
					}
				},
				complete: () => {
					if (options && options.complete) {
						options.complete()
					}
				}
			})
		},
		// 关闭所有页面，打开到应用内的某个页面
		mxReLaunch(options) {
			if (options && typeof options === "string") {
				options = {
					url: options
				}
			}
			if (!options || !options.url) {
				this.mxToast("Url不能为空!")
				return false
			}
			options.url = options.params ? `${options.url}?${this.$tools.jsonToUrlParams(options.params)}` : options.url
			uni.reLaunch({
				url: options.url,
				success: () => {
					if (options && options.success) {
						options.success()
					}
				},
				fail: () => {
					if (options && options.fail) {
						options.fail()
					}
				},
				complete: () => {
					if (options && options.complete) {
						options.complete()
					}
				}
			})
		},
		// 跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面
		mxSwitchTab(options) {
			if (options && typeof options === "string") {
				options = {
					url: options
				}
			}
			if (!options || !options.url) {
				this.mxToast("Url不能为空!")
				return false
			}
			uni.switchTab({
				url: options.url,
				success: () => {
					if (options && options.success) {
						options.success()
					}
				},
				fail: () => {
					if (options && options.fail) {
						options.fail()
					}
				},
				complete: () => {
					if (options && options.complete) {
						options.complete()
					}
				}
			});
		},
		// 关闭当前页面，返回上一页面或多级页面
		mxNavigateBack(options) {
			if (options && options >= 1) {
				options = {
					delta: options
				}
			}
			uni.navigateBack({
				delta: options && options.delta || 1,
				success: () => {
					if (options && options.success) {
						options.success()
					}
				},
				fail: () => {
					if (options && options.fail) {
						options.fail()
					}
				},
				complete: () => {
					if (options && options.complete) {
						options.complete()
					}
				}
			})
		},
		// 返回的判断
		mxNavigateToOrBack(options) {
			let currentRoutes = getCurrentPages()
			if (currentRoutes && currentRoutes.length > 1) {
				this.mxNavigateBack()
			} else {
				if (!options) {
					return false
				} else if (!options.url) {
					this.mxToast("Url不能为空!")
					return false
				}
				this.mxNavigateTo(options)
			}
		},
		// 转换时间为天，小时，分钟
		mxTranceTimeToDay(beginTime, endTime) {
			let desc = ""
			if (moment(beginTime).isValid() && moment(endTime).isValid()) {
				let msDay = 86400 * 1000 // 1天的毫秒数
				let mBegin = moment(beginTime)
				let mEnd = moment(endTime)
				let mDur = mEnd.diff(mBegin, "ms") // 相差的毫秒数
				mDur = Math.abs(mDur)
				let showDay = Math.floor(mDur / msDay) // 最大显示多少天
				let msRemain = mDur % msDay // 剩余时间毫秒
				let dayDesc = showDay > 0 ? showDay + "天" : ""
				let dur = moment.duration(msRemain, "ms")
				let hours = dur.hours()
				let hoursDesc = hours > 0 ? hours + "小时" : ""
				let minutes = dur.minutes()
				let minutesDesc = minutes > 0 ? minutes + "分钟" : ""
				desc = dayDesc + hoursDesc + minutesDesc
				return desc
			}
		}
	}
}